/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.ugame.module.store;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.model.bl.StoreService;
import vn.ugame.model.entity.Image;
import vn.ugame.module.AbstractModule;
import vn.ugame.module.ActionConfig;
import vn.ugame.module.Module;
import vn.ugame.module.Param;

/**
 *
 * @author user
 */
public class ImageModule extends AbstractModule implements Module {

    public ImageModule() {
    }

    @ActionConfig(urlPattern = {"^(?<itemId>\\w+)/(?<type>\\d+)/?$"})
    public void displayItemImage(@Param("itemId") String itemId, @Param("type") int type){
        try {
            //Declare service
            StoreService service = new StoreService(getConfig().getLocale());

            //Find item image
            Image image = service.findImage(itemId, type);
            //Process item image not found
            if (image == null) {
                getResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            //Get real path of item image
            String fileName = getContext().getRealPath(image.getPath());
            //Set content size
            File file = new File(fileName);
            //Get mine type of the image
            String mimeType = getContext().getMimeType(fileName);
            //Process mine type of image not found
            if (mimeType == null) {
                getContext().log("Could not get MIME type of " + fileName);
                getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }
            //Set content type
            getResponse().setContentType(mimeType);            
            getResponse().setContentLength((int) file.length());
            //Set header
            getResponse().setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
            //Open the file and output streams
            FileInputStream in = new FileInputStream(file);
            OutputStream out = getResponse().getOutputStream();
            //Copy the contents of the file to the output stream
            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = in.read(buf)) >= 0) {
                out.write(buf, 0, count);
                out.flush();
            }
            //Close all streams
            in.close();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
